<template>
  <span class="dict-select">
    <template v-if="type == 'text'">
      <template v-for="item in list">
        <template v-if="modelValue == item.dictValue">
          <span
            v-if="item.listClass == 'default' || !item.listClass"
            :key="item.dictValue"
            :class="item.cssClass"
          >{{ item.dictLabel }}</span>
          <el-tag
            v-else
            :key="item.dictValue + ''"
            :type="item.listClass == 'primary' ? '' : item.listClass"
            :class="item.cssClass"
          >
            {{ item.dictLabel }}
          </el-tag>
        </template>
      </template>
    </template>
    <el-checkbox-group v-else-if="type == 'checkbox'" :model-value="valueTmp" @change="change">
      <el-checkbox v-for="dict in list" :key="dict.dictValue" :label="dict[resolveValue]">{{
        dict.dictLabel
      }}</el-checkbox>
    </el-checkbox-group>
    <el-radio-group
      v-else-if="type == 'radio'"
      :model-value="valueTmp"
      :disabled="disabled"
      @change="change"
    >
      <el-radio-button v-for="dict in list" :key="dict.dictValue" :label="dict[resolveValue]">{{
        dict.dictLabel
      }}</el-radio-button>
    </el-radio-group>
    <el-select
      v-else
      :multiple="multi"
      :model-value="valueTmp"
      :clearable="!noClear"
      collapse-tags
      :placeholder="placeholder"
      :disabled="disabled"
      @change="change"
    >
      <el-option
        v-for="dict in list"
        :key="dict.dictValue"
        :label="dict.dictLabel"
        :value="dict[resolveValue]"
      />
    </el-select>
  </span>
</template>
<script>
  import useDictStore from '@/store/modules/dict'
  export default {
    name: 'DictSelect',
    props: {
      dictName: String,
      placeholder: {
        type: String,
        default: '请选择'
      },
      disabled: {
        type: Boolean,
        default: false
      },
      dictList: {
        type: Array,
        default: () => []
      },
      noClear: {
        type: Boolean,
        default: false
      },
      type: String,
      multi: {
        type: Boolean,
        default: false
      },
      resolveValue: {
        type: String,
        default: 'dictValue'
      },
      modelValue: [Number, String, Array, Boolean]
    },
    emits: ['update:modelValue', 'change'],
    data() {
      return {}
    },
    computed: {
      valueTmp() {
        return this.modelValue
      },
      list() {
        const store = useDictStore()
        return this.dictName ? store.dictList(this.dictName) : this.dictList
      }
    },
    methods: {
      change(v) {
        this.valueTmp = v
        this.$emit('update:modelValue', v)
        this.$emit('change', v)
      }
    }
  }
</script>
<style lang="less" scoped>
  .el-form-item .dict-select {
    display: block;
    width: 100%;
  }
  .full {
    width: 100%;
  }
</style>
